//
//  YWYoukuDetailController.m
//  videoTest3
//
//  Created by jun peng on 2022/7/13.
//

#import "YWYoukuDetailController.h"
#import "YWKLineCheatsVideoListParam.h"
#import "YWKLineCheatsVideoListStatus.h"
#import "YWKLineCheatsVideoListResultStatus.h"
#import "YWKLineCheatsVideoListPageStatus.h"
#import "YWKLineCheatsVideoListDataStatus.h"
#import "YWKLineCheatsVideoListTool.h"
#import "YWKLineCheatsClassCell.h"

#import "YWNoContentView2.h"
#import "YWYoukuDetailHeaderView.h"
#import "YWVideoView3.h"

#import "YWLittleWindowVedioView.h"
#import "AppDelegate.h"

#import "YWDownloadController2.h"
#import "YWDownloadController.h"
#import "YWDownloadController3.h"

#import "YWDownloadManager3.h"
#import "YWDownloadStatus3.h"
//#import <TXLiteAVSDK_Player/TXLiteAVSDK.h>

#define headerViewHeight (headerViewVedioViewHeight + 45)

#define littleWindowInterval 5
@interface YWYoukuDetailController ()<UITableViewDelegate,UITableViewDataSource,YWYoukuDetailHeaderViewDelegate,YWVideoView3Delegate,NSURLSessionDelegate,NSURLSessionDownloadDelegate/*,TXVodDownloadDelegate*/,YWKLineCheatsClassCellDelegate,CAAnimationDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *barConstraintHeight;
@property (weak, nonatomic) IBOutlet YWTableView *tableView;

@property(nonatomic,strong)NSMutableArray *statusArray;

@property(nonatomic,weak)YWYoukuDetailHeaderView *headerView;

@property (nonatomic, strong) UIView * vedioBgView; // 播放器BgView
@property (nonatomic, strong) YWVideoView3 * vedioView; // 播放器

//小窗口
@property(nonatomic,strong)YWLittleWindowVedioView *littleWindowVedioView;

//正在播放的头部选播视频
@property(nonatomic,strong)YWKLineCheatsVideoListDataStatus *selectedPlayingHeaderStatus;

//选中列表哪一个的、主要是为了修改列表cell样式用的、和上面的不一样
@property(nonatomic,strong)YWKLineCheatsVideoListDataStatus *selectedListStatus;

//这个手势为了全屏时覆盖和阻止返回手势
@property(nonatomic,strong)UIPanGestureRecognizer *panGesture;

@property(nonatomic,strong)MBProgressHUD *hud;
@property(nonatomic,strong)NSURLSession *session;

//@property(nonatomic,assign)BOOL isFirstAppear;

@property(nonatomic,strong)NSMutableArray *imageViews;

@property (weak, nonatomic) IBOutlet UILabel *countLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *countLabelWidthConstraint;


@end

@implementation YWYoukuDetailController

-(NSMutableArray*)imageViews{

    if (_imageViews == nil) {
        _imageViews = [NSMutableArray array];
    }
    return _imageViews;
}



-(NSURLSession *)session{
    if (_session == nil) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    }
    return _session;
}

//点击保存相册
-(void)headerViewDidClickSaveToAlbum:(YWYoukuDetailHeaderView *)headerView{
    
    self.hud = [MBProgressHUD showMessage:nil toView:self.view];
    
    
    [YWVideoPlayerManager videoPlayWithKLineCheatsVideoListDataStatus:self.selectedPlayingHeaderStatus canPlayLoacalWithFullPathBlock:^(NSString * _Nonnull fullPath) {
        
        
        //在本地的视频资源
        //直接保存到相册
        UISaveVideoAtPathToSavedPhotosAlbum(fullPath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
        
//        [self.hud hide:YES afterDelay:1.0];
        [self.hud hideAnimated:YES afterDelay:1.0];
        
    } onlyCanPlayWebWithVideoUrlBlock:^(NSString * _Nonnull videoUrl) {
        
        
//        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.vedioView.urlString] cachePolicy:1.0 timeoutInterval:5.0];
        
        //网上的、不是在本地的视频资源
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:videoUrl] cachePolicy:1.0 timeoutInterval:5.0];
        
        //下载任务
        [[self.session downloadTaskWithRequest:request] resume];
        
        NSURLSessionDownloadTask *task = [self.session downloadTaskWithURL:[NSURL URLWithString:self.vedioView.urlString] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            //下载完成走这里
            dispatch_async(dispatch_get_main_queue(), ^{
                
//                [self.hud hide:YES afterDelay:0.0];
                
                [self.hud hideAnimated:YES afterDelay:0.0];
                
                [MBProgressHUD showSuccess:@"下载成功"];
                
             });
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSString *documents= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
            
            NSString *path = [documents stringByAppendingPathComponent:response.suggestedFilename];
            
            //视频存放到这个位置(从tmp文件夹移动到document文件夹)
            [fileManager moveItemAtURL:location toURL:[NSURL fileURLWithPath:path] error:nil];
            
            //保存到相册
            UISaveVideoAtPathToSavedPhotosAlbum(path, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
            
            YWLog(@"location:%@",location);
            YWLog(@"path:%@",path);
        }];
        
        //开始下载任务
        [task resume];
        
        
        
    }];
    
    
  
    
    
}

//保存到相册完成走这里
-(void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void*)contextInfo{
        
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!error) {
            [MBProgressHUD showSuccess:@"保存相册成功"];
            
        }
        else{
            [MBProgressHUD showError:@"保存相册失败"];
            
        }
    });
    
}

//下载进度代理
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    float progress = (float)totalBytesWritten/totalBytesExpectedToWrite;
    
    long pro = (long)(progress * 100);
    
    self.hud.label.text = [NSString stringWithFormat:@"下载进度：%ld%%，期间不要退出应用，等下载完成到沙盒就能马上保存到相册",pro];
    self.hud.label.font = [UIFont systemFontOfSize:12];
    
//    [self.hud setLabelText:[NSString stringWithFormat:@"下载进度：%ld%%，期间不要退出应用，等下载完成到沙盒就能马上保存到相册",pro]];
//    [self.hud setLabelFont:[UIFont systemFontOfSize:12]];
    
    YWLog(@"progress: %f",progress);
}


//点击下载的
-(void)headerViewDidClickDownload:(YWYoukuDetailHeaderView *)headerView{
    
     [YWDownloadManager3 judgeStatusExistInDataBase:self.selectedPlayingHeaderStatus.VideoUrl ifNoExist:^{
 
         YWDownloadManager3 *manager = [YWDownloadManager3 sharedownloadManager];
 
         YWDownloadStatus3 *dStatus = [[YWDownloadStatus3 alloc] init];
         dStatus.downloadType = YWDownloadType_Waiting3;
         dStatus.Title = self.selectedPlayingHeaderStatus.Title;
         dStatus.PicUrl = self.selectedPlayingHeaderStatus.PicUrl;
         dStatus.Id = self.selectedPlayingHeaderStatus.Id;
         dStatus.VideoUrl = self.selectedPlayingHeaderStatus.VideoUrl;
 
         [manager createOneDataTaskWithStatus:dStatus];
         
         
         //贝塞尔曲线动画
         [self joinDownloadWithBerzierAnimation];
         
         
         //发送通知改变KLineCheatsVideoListCell状态
         [[NSNotificationCenter defaultCenter] postNotificationName:YWChangeKLineCheatsVideoListTypeNote object:self userInfo:@{YWVideoUrlKey:dStatus.VideoUrl,YWKLineCheatsVideoListTypeKey:@(YWKLineCheatsVideoList_Downloading3)}];
     }];
//    YWDownloadController2 *vc = [[YWDownloadController2 alloc] initWithNibName:@"YWDownloadController2" bundle:nil];
//    vc.downloadStatus = self.selectedPlayingHeaderStatus;
//    [self.navigationController pushViewController:vc animated:YES];
    
//    TXVodDownloadManager *downloader = [TXVodDownloadManager shareInstance];
//
//    NSString *documents= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//
//    YWLog(@"documents - %@",documents);
//
//    NSString *path = [documents stringByAppendingPathComponent:@"000000.mp4"];
//
//    [downloader setDownloadPath:path];
//
//    TXVodDownloadMediaInfo *info = [downloader startDownload:@"test" url:self.vedioView.urlString];
//
//    YWLog(@"abc - %@",info);
//
//    downloader.delegate = self;
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
//    if (self.isFirstAppear == YES) {
//
//        self.isFirstAppear = NO;
//        return;
//    }
    
    //进来不是播放状态（包括不是暂停状态才需要播放）
    if (!self.vedioView.isPlaying_containPause) {
        //播放
        [self pagerViewScrollToTop];
        
        self.littleWindowVedioView.hidden = YES;
        
        self.vedioView.status = self.selectedPlayingHeaderStatus;
        
        
        [YWVideoPlayerManager videoPlayWithKLineCheatsVideoListDataStatus:self.selectedPlayingHeaderStatus canPlayLoacalWithFullPathBlock:^(NSString * _Nonnull fullPath) {
            
            [self.vedioView startPlayWithUrl:fullPath withMute:NO];
        } onlyCanPlayWebWithVideoUrlBlock:^(NSString * _Nonnull videoUrl) {
            
            [self.vedioView startPlayWithUrl:videoUrl withMute:NO];
        }];
        
        
//        [self.vedioView startPlayWithUrl:self.selectedPlayingHeaderStatus.VideoUrl withMute:NO];
        
        [self.tableView addSubview:self.vedioBgView];
        
        self.vedioBgView.frame = CGRectMake(0, 0, Wi, headerViewVedioViewHeight);
        
        self.vedioView.frame = self.vedioBgView.bounds;

        self.vedioBgView.layer.cornerRadius = 0;
        
        self.vedioBgView.clipsToBounds = YES;

        self.vedioBgView.hidden = NO;
    }
    
   
    
}


//-(void)onDownloadStart:(TXVodDownloadMediaInfo *)mediaInfo{
//    YWLog(@"abc - onDownloadStart");
//}
//
//-(void)onDownloadProgress:(TXVodDownloadMediaInfo *)mediaInfo{
//    YWLog(@"abc - onDownloadProgress");
//}
//-(void)onDownloadStop:(TXVodDownloadMediaInfo *)mediaInfo{
//    YWLog(@"abc - onDownloadStop");
//}
//-(void)onDownloadFinish:(TXVodDownloadMediaInfo *)mediaInfo{
//    YWLog(@"abc - onDownloadFinish");
//}
//-(void)onDownloadError:(TXVodDownloadMediaInfo *)mediaInfo errorCode:(TXDownloadError)code errorMsg:(NSString *)msg{
//    YWLog(@"abc - onDownloadError code:%ld,msg:%@",(long)code,msg);
//}


-(UIPanGestureRecognizer *)panGesture{
    if (_panGesture == nil) {
        
        _panGesture = [[UIPanGestureRecognizer alloc] init];
        
        [self.view addGestureRecognizer:self.panGesture];
    }
    return _panGesture;
}

-(YWLittleWindowVedioView *)littleWindowVedioView{
    if (_littleWindowVedioView == nil) {
        _littleWindowVedioView = [YWLittleWindowVedioView videoView];
        
        _littleWindowVedioView.backgroundColor = [UIColor blackColor];
        
        CGFloat w = Wi/2.5;
        CGFloat h = w/1.5;
        CGFloat y = self.view.height - h - littleWindowInterval - h;
        CGFloat x = Wi - w - littleWindowInterval;
        
        _littleWindowVedioView.frame = CGRectMake(x, y, w, h);
        
        [self.view addSubview:_littleWindowVedioView];
        
        _littleWindowVedioView.hidden = YES;
        
        _littleWindowVedioView.layer.cornerRadius = 5;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(littleWindowVedioViewTap)];
        
        [_littleWindowVedioView addGestureRecognizer:tap];
        
        
        UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
        [_littleWindowVedioView addGestureRecognizer:pan];
        
        
    }
    return _littleWindowVedioView;
}

-(void)pan:(UIPanGestureRecognizer *)pan{
 
    CGPoint transP = [pan translationInView:self.view];
    
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
        {

            
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            
            self.littleWindowVedioView.center = CGPointMake(self.littleWindowVedioView.centerX + transP.x, self.littleWindowVedioView.centerY + transP.y);
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
           
            if (self.littleWindowVedioView.centerX > Wi/2) {
                
                [UIView animateWithDuration:0.3 animations:^{
                    self.littleWindowVedioView.centerX = Wi - self.littleWindowVedioView.width/2 - littleWindowInterval;
              
                }];
                
            }
            else{
                [UIView animateWithDuration:0.3 animations:^{
                    self.littleWindowVedioView.centerX = self.littleWindowVedioView.width/2 + littleWindowInterval;
              
                }];
                
            }
            if (self.littleWindowVedioView.y < self.navBar.height + littleWindowInterval) {
                
                [UIView animateWithDuration:0.3 animations:^{
                    self.littleWindowVedioView.y = self.navBar.height + littleWindowInterval;
              
                }];
                
            }
            
            if (self.littleWindowVedioView.y > self.view.height - self.littleWindowVedioView.height - littleWindowInterval - 30) {
                
                [UIView animateWithDuration:0.3 animations:^{
                    self.littleWindowVedioView.y = self.view.height - self.littleWindowVedioView.height - littleWindowInterval - 30;
              
                }];
                
            }
            
           
        }
            break;
            
        default:
            break;
    }
    
    //复位.
    [pan setTranslation:CGPointZero inView:self.view];
    
}

-(NSMutableArray *)statusArray{
    if (_statusArray == nil) {
        _statusArray = [NSMutableArray array];
    }
    return _statusArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navBar.title = @"优酷详情";
    self.barConstraintHeight.constant = self.navBar.frame.size.height;
    
    [self setupRightItem];
    UIView *headerBgView = [[UIView alloc] init];
    
    YWYoukuDetailHeaderView *headerView = [YWYoukuDetailHeaderView headerView];
    
    self.headerView = headerView;
    headerView.delegate = self;
    
    [headerBgView addSubview:headerView];
    
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
           
       make.left.equalTo(headerView.superview).with.offset(0);
       make.right.equalTo(headerView.superview).with.offset(0);
       make.bottom.equalTo(headerView.superview).with.offset(0);
       make.top.equalTo(headerView.superview).with.offset(0);
      
    }];
    
    headerBgView.frame = CGRectMake(0, 0, Wi, headerViewHeight);
    
    self.tableView.tableHeaderView = headerBgView;
    
    
    // 创建播放器
    self.vedioView = [YWVideoView3 videoView];
    self.vedioView.delegate = self;
    self.vedioBgView = [UIView new];
    [self.tableView addSubview:self.vedioBgView];
    self.vedioBgView.backgroundColor = [UIColor blackColor];
    self.vedioView.backgroundColor = [UIColor blackColor];
    [self.vedioBgView addSubview:self.vedioView];
    self.vedioBgView.frame = CGRectMake(0, 0, Wi, headerViewVedioViewHeight);
    self.vedioView.frame = self.vedioBgView.bounds;
    
    //指着保存
    self.selectedPlayingHeaderStatus = self.status;
    //播放
    
    YWLog(@"aaa - %@",self.selectedPlayingHeaderStatus.VideoUrl);
    //其实这个判断放在单例Manager好一点
    if (self.status.VideoUrl != nil) {
        self.vedioView.status = self.selectedPlayingHeaderStatus;
        
        [YWVideoPlayerManager videoPlayWithKLineCheatsVideoListDataStatus:self.selectedPlayingHeaderStatus canPlayLoacalWithFullPathBlock:^(NSString * _Nonnull fullPath) {
            
            [self.vedioView startPlayWithUrl:fullPath withMute:NO];
        } onlyCanPlayWebWithVideoUrlBlock:^(NSString * _Nonnull videoUrl) {
            
            [self.vedioView startPlayWithUrl:videoUrl withMute:NO];
        }];
        
        
        
//        [self.vedioView startPlayWithUrl:self.status.VideoUrl withMute:NO];
        
    }
    [self loadVideoNewData];
    
//    self.isFirstAppear = YES;
    
    [self.view bringSubviewToFront:self.countLabel];
    self.countLabel.layer.cornerRadius = 8;
    self.countLabel.clipsToBounds = YES;
    self.countLabelWidthConstraint.constant = [self getWidthWithBtnContent:self.countLabel];
    
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDownloadBadgeValue) name:YWGetDownloadBadgeValueNote object:nil];
    
    
    //监听通知改变KLineCheatsVideoListCell状态
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeKLineCheatsVideoListTypeNote:) name:YWChangeKLineCheatsVideoListTypeNote object:nil];
}

-(void)changeKLineCheatsVideoListTypeNote:(NSNotification *)notification{
    
    NSString *videoUrl = notification.userInfo[YWVideoUrlKey];
    NSNumber *kLineCheatsVideoListTypeNum = notification.userInfo[YWKLineCheatsVideoListTypeKey];
    
    //这样遍历还是会卡一下的、但是我又不想用刷新的办法，那没办法了、除非你要像下载Manager一样Manager和VC引用同一个模型数组、引用同一个对象、单改Manager的模型数组
    for (YWKLineCheatsVideoListDataStatus *status in self.statusArray) {
        if ([status.VideoUrl isEqualToString:videoUrl]) {
            status.kLineCheatsVideoListType = kLineCheatsVideoListTypeNum.integerValue;
         
        }
    }
    
   
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getDownloadBadgeValue];
}

-(void)getDownloadBadgeValue{
    
    YWDownloadManager3 *manager = [YWDownloadManager3 sharedownloadManager];
    NSInteger count = [manager getDownloadingTaskCount];
    
        if (count > 0) {
            [self.countLabel setHidden:NO];
    
            self.countLabel.text = [NSString stringWithFormat:@"%ld", count];
    
            self.countLabelWidthConstraint.constant = [self getWidthWithBtnContent:self.countLabel];
    
        } else {
            [self.countLabel setHidden:YES];
        }
    
}

-(CGFloat)getWidthWithBtnContent:(UILabel*)label{
    
    NSString *content = label.text;
    UIFont *font = label.font;
    CGSize size = CGSizeMake(MAXFLOAT, 16.0f);
    CGSize buttonSize = [content boundingRectWithSize:size
                                              options:NSStringDrawingTruncatesLastVisibleLine  | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                           attributes:@{ NSFontAttributeName:font}
                                              context:nil].size;
    return buttonSize.width + 10;
}



-(void)setupRightItem{
    
    UIButton *rightItem = [[UIButton alloc] init];
    [rightItem setTitle:@"下载列表" forState:UIControlStateNormal];
    [rightItem setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [followBtn setImage:[UIImage imageNamed:@"消息关注"] forState:UIControlStateNormal];
    //    self.navBar.navBarTintColor = otherMainColor;
    rightItem.bounds = CGRectMake(0, 0, 180, 44);
    rightItem.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    //    locationBtn.imagei = UIEdgeInsetsMake(0, -10, 0, 0);
//    [followBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 13)];
    [rightItem setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 8)];
    self.navBar.rightItem = rightItem;
    rightItem.titleLabel.font = [UIFont systemFontOfSize:14];
    [rightItem addTarget:self action:@selector(gotoDownloadList) forControlEvents:UIControlEventTouchUpInside];
}

-(void)gotoDownloadList{
    
    YWDownloadController3 *vc = [[YWDownloadController3 alloc] initWithNibName:@"YWDownloadController3" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
    
}



-(void)loadVideoNewData{
    
    YWKLineCheatsVideoListParam *param = [[YWKLineCheatsVideoListParam alloc] init];
    
    if (self.meStatus.isLogin == YES) {
        param.phone = self.meStatus.userStatus.Phone;
    }
    else{
        param.phone = @"";
        
    }
    
    [YWKLineCheatsVideoListTool kLineCheatsVideoListStatusesWithParameters:param success:^(YWKLineCheatsVideoListStatus * _Nonnull status) {
        
        [self.noContentView removeFromSuperview];
        
               [self.tableView.mj_header endRefreshing];
        
               if (status.IsSuccess.integerValue == 1) {
                   
                   self.statusArray = [NSMutableArray arrayWithArray:status.ResultObj.PageInfo.VideoList];
                   
                
                   [self.tableView reloadData];
                   
                   
               }
               else{
                   
                   self.statusArray = [NSMutableArray array];
                   
                   [self.tableView reloadData];
                   
                   
                   
                   [self.view addSubview:self.noContentView];
                   
                   self.noContentView.frame = CGRectMake(0, 0, Wi, self.view.height);
                   
                   self.noContentView.noContentType = YWNoContentView2Type_NoContent;
                   
                   
                   
               }
        
    } failure:^(NSError * _Nonnull error) {
        
        [self.tableView.mj_header endRefreshing];
//              [MBProgressHUD showError:@"服务器繁忙，请稍后再试"];
        
        [self.view addSubview:self.noContentView];
        
        self.noContentView.frame = CGRectMake(0, 0, Wi, self.view.height);
        
        self.noContentView.noContentType = YWNoContentView2Type_Error404;
    }];
    

    
    
}


-(void)noContentView2DidClickRefreshBtn:(YWNoContentView2 *)noContentView2{
    
    [self loadVideoNewData];
    
}



-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    //这里用isPlaying不用isPlaying_containPause
    if (self.vedioView.isPlaying == YES) {  //headerView正在播放中
      
        if (scrollView.contentOffset.y >= headerViewVedioViewHeight) {
            
            //这样就可以保证只执行一次、因为你滚动过程不断掉用continue会造成卡顿的
            if (self.littleWindowVedioView.hidden == YES) {
                
                self.littleWindowVedioView.hidden = NO;
                
                //继续播放不需要判断本地存不存在、原来用fullPath还是videoUrl就用回之前的、也就是self.vedioView.urlString
                [self.littleWindowVedioView continuePlayWithAnthorViewWithUrl:self.vedioView.urlString WithMute:NO];
            }
            
        }
        else{
            
            //这样就可以保证只执行一次、因为你滚动过程不断掉用continue会造成卡顿的
            if (self.littleWindowVedioView.hidden == NO) {
                
                self.littleWindowVedioView.hidden = YES;
                
                //继续播放不需要判断本地存不存在、原来用fullPath还是videoUrl就用回之前的、也就是self.vedioView.urlString
                [self.vedioView continuePlayWithAnthorViewWithUrl:self.vedioView.urlString WithMute:NO];
            }
            
         
        }
    }
}



-(void)littleWindowVedioViewTap{
    
    [self pagerViewScrollToTop];
   
}


- (void)pagerViewScrollToTop{
    
    [self.tableView setContentOffset:CGPointZero animated:YES];
}



-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    //强制竖屏
    [self setViewOrientation:UIInterfaceOrientationPortrait];
    
}



- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    //这个无论是不是去横视频界面都去隐藏vedioBgView
    self.vedioBgView.hidden = YES;
    
    [self.vedioView stopPlay];
    
    //让整个程序不能旋转
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotate = 0;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YWKLineCheatsVideoListDataStatus *dataStatus = self.statusArray[indexPath.row];
    
    YWKLineCheatsClassCell *cell = [YWKLineCheatsClassCell cellWithTableView:tableView];
    cell.delegate = self;
    cell.status = dataStatus;
    return cell;

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.statusArray.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 105;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self pagerViewScrollToTop];
    
    YWKLineCheatsVideoListDataStatus *status = self.statusArray[indexPath.row];
    
    //这里有可能是点击选播传过来的、所以要保存
    self.selectedPlayingHeaderStatus = status;

    //改变cell样式
    self.selectedListStatus.isSelect = NO;
    status.isSelect = YES;
    self.selectedListStatus = status;
    [self.tableView reloadData];

    self.littleWindowVedioView.hidden = YES;

    self.vedioView.status = self.selectedPlayingHeaderStatus;
    
    
    [YWVideoPlayerManager videoPlayWithKLineCheatsVideoListDataStatus:self.selectedPlayingHeaderStatus canPlayLoacalWithFullPathBlock:^(NSString * _Nonnull fullPath) {
        
            [self.vedioView startPlayWithUrl:fullPath withMute:NO];
    } onlyCanPlayWebWithVideoUrlBlock:^(NSString * _Nonnull videoUrl) {
        
        [self.vedioView startPlayWithUrl:videoUrl withMute:NO];
    }];

   
    
//    [self.vedioView startPlayWithUrl:videoUrl withMute:NO];
    
    

    
    
    [self.tableView addSubview:self.vedioBgView];

    self.vedioBgView.frame = CGRectMake(0, 0, Wi, headerViewVedioViewHeight);

    self.vedioView.frame = self.vedioBgView.bounds;

    self.vedioBgView.layer.cornerRadius = 0;

    self.vedioBgView.clipsToBounds = YES;

    self.vedioBgView.hidden = NO;
    
    
}

-(void)lineCheatsClassCellClickDownload:(YWKLineCheatsClassCell *)kLineCheatsClassCell withStatus:(YWKLineCheatsVideoListDataStatus *)status{
       
        [YWDownloadManager3 judgeStatusExistInDataBase:status.VideoUrl ifNoExist:^{
    
            YWDownloadManager3 *manager = [YWDownloadManager3 sharedownloadManager];
    
            YWDownloadStatus3 *dStatus = [[YWDownloadStatus3 alloc] init];
            dStatus.downloadType = YWDownloadType_Waiting3;
            dStatus.Title = status.Title;
            dStatus.PicUrl = status.PicUrl;
            dStatus.Id = status.Id;
            dStatus.VideoUrl = status.VideoUrl;
    
            [manager createOneDataTaskWithStatus:dStatus];
            
            
            //贝塞尔曲线动画
            [self berzierAnimationWithCell:kLineCheatsClassCell andIconView:kLineCheatsClassCell.iconView];
            
            //发送通知改变KLineCheatsVideoListCell状态
            [[NSNotificationCenter defaultCenter] postNotificationName:YWChangeKLineCheatsVideoListTypeNote object:self userInfo:@{YWVideoUrlKey:dStatus.VideoUrl,YWKLineCheatsVideoListTypeKey:@(YWKLineCheatsVideoList_Downloading3)}];
        }];
    
}

-(void)joinDownloadWithBerzierAnimation{
    
    //0、转换父控件所在位置
    CGRect rects = [self.tableView convertRect:self.vedioBgView.frame toView:[UIApplication sharedApplication].keyWindow];
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:imageView];
    imageView.frame = rects;
    //用数组装着imageView,等动画结束就销毁imageView
    [self.imageViews addObject:imageView];
     [self.vedioView snapshot:^(UIImage * _Nonnull image) {
         imageView.image = image;
         if (image == nil) {
             imageView.image = [UIImage imageWithColor:YWColor(250, 250, 250)];
         }
    }];
  
    
    //1、圆角动画
    CABasicAnimation *cornerRadiusAnimation = [CABasicAnimation animation];
    cornerRadiusAnimation.keyPath = @"cornerRadius";
    cornerRadiusAnimation.fromValue = @(self.vedioBgView.layer.cornerRadius);
    cornerRadiusAnimation.toValue = @(self.vedioBgView.height/2);
//    [cornerRadiusAnimation setDuration:0.3];
//    [cornerRadiusAnimation setBeginTime:0.0];
    cornerRadiusAnimation.removedOnCompletion = NO;
    cornerRadiusAnimation.fillMode = kCAFillModeForwards;
    
    
//    CABasicAnimation *widthAnimation = [CABasicAnimation animation];
//    widthAnimation.keyPath = @"transform.scale.x";
//    widthAnimation.toValue = @(iconView.height*1.0/iconView.width);
//    [widthAnimation setDuration:0.3];
//    [widthAnimation setBeginTime:0.0];
//    widthAnimation.removedOnCompletion = NO;
//    widthAnimation.fillMode = kCAFillModeForwards;
    
    //2、曲线动画
    CGFloat desX = Wi - 50;
    CGFloat desY = self.navBar.height;
    CGPoint startPoint = CGPointMake(rects.origin.x+rects.size.width/2, rects.origin.y+rects.size.height/2);
    CGPoint endpoint = CGPointMake(desX, desY);
    //控制曲线弧度幅度的点
    CGPoint controlPoint = CGPointMake(Wi/2, He);
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:startPoint];
    [path addQuadCurveToPoint:endpoint controlPoint:controlPoint];
    //创建关键帧
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = path.CGPath;
//    [animation setDuration:0.6];
//    [animation setBeginTime:0.4];
    
    //3、创建缩放动画对象
    CABasicAnimation *scale = [CABasicAnimation animation];
    scale.keyPath = @"transform.scale";
    scale.toValue = @(0.1);
//    [animation setDuration:0.6];
//    [animation setBeginTime:0.4];

    //4、将所有的动画添加到动画组中
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.animations = @[/*widthAnimation,*/cornerRadiusAnimation,animation, scale];
    group.duration = 1;
    group.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    group.delegate = self;
    //当动画完成，停留到结束位置
    group.removedOnCompletion = NO;
    group.fillMode = kCAFillModeForwards;
    [imageView.layer addAnimation:group forKey:@"headerView"];
    path = nil;
    
}

-(void)berzierAnimationWithCell:(UITableViewCell*)cell andIconView:(UIImageView *)iconView{
    
    //0、转换父控件所在位置
    CGRect rects = [cell.contentView convertRect:iconView.frame toView:[UIApplication sharedApplication].keyWindow];
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:imageView];
    imageView.frame = rects;
    //用数组装着imageView,等动画结束就销毁imageView
    [self.imageViews addObject:imageView];
    imageView.image = iconView.image;
    if (iconView.image == nil) {
        imageView.image = [UIImage imageWithColor:YWColor(250, 250, 250)];
    }
    
    //1、圆角动画
    CABasicAnimation *cornerRadiusAnimation = [CABasicAnimation animation];
    cornerRadiusAnimation.keyPath = @"cornerRadius";
    cornerRadiusAnimation.fromValue = @(iconView.layer.cornerRadius);
    cornerRadiusAnimation.toValue = @(iconView.height/2);
//    [cornerRadiusAnimation setDuration:0.3];
//    [cornerRadiusAnimation setBeginTime:0.0];
    cornerRadiusAnimation.removedOnCompletion = NO;
    cornerRadiusAnimation.fillMode = kCAFillModeForwards;
    
    
//    CABasicAnimation *widthAnimation = [CABasicAnimation animation];
//    widthAnimation.keyPath = @"transform.scale.x";
//    widthAnimation.toValue = @(iconView.height*1.0/iconView.width);
//    [widthAnimation setDuration:0.3];
//    [widthAnimation setBeginTime:0.0];
//    widthAnimation.removedOnCompletion = NO;
//    widthAnimation.fillMode = kCAFillModeForwards;
    
    //2、曲线动画
    CGFloat desX = Wi - 50;
    CGFloat desY = self.navBar.height;
    CGPoint startPoint = CGPointMake(rects.origin.x+rects.size.width/2, rects.origin.y+rects.size.height/2);
    CGPoint endpoint = CGPointMake(desX, desY);
    //控制曲线弧度幅度的点
    CGPoint controlPoint = CGPointMake(Wi/2, He);
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:startPoint];
    [path addQuadCurveToPoint:endpoint controlPoint:controlPoint];
    //创建关键帧
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = path.CGPath;
//    [animation setDuration:0.6];
//    [animation setBeginTime:0.4];
    
    //3、创建缩放动画对象
    CABasicAnimation *scale = [CABasicAnimation animation];
    scale.keyPath = @"transform.scale";
    scale.toValue = @(0.1);
//    [animation setDuration:0.6];
//    [animation setBeginTime:0.4];

    //4、将所有的动画添加到动画组中
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.animations = @[/*widthAnimation,*/cornerRadiusAnimation,animation, scale];
    group.duration = 1;
    group.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    group.delegate = self;
    //当动画完成，停留到结束位置
    group.removedOnCompletion = NO;
    group.fillMode = kCAFillModeForwards;
    [imageView.layer addAnimation:group forKey:nil];
    path = nil;
    
}

#pragma mark - 动画的代理方法
-(void)animationDidStart:(CAAnimation *)anim{

}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{

   // 等动画结束就销毁第一个imageView，这样不会占内存了
   UIImageView *imageView = [self.imageViews firstObject];
    [imageView removeFromSuperview];
    [self.imageViews removeObject:imageView];

    NSLog(@"==%lu ==%lu",(unsigned long)self.view.window.subviews.count,(unsigned long)self.imageViews.count);
    
    //发送通知改badgeValue
    [[NSNotificationCenter defaultCenter] postNotificationName:YWGetDownloadBadgeValueNote object:self userInfo:nil];
    
    
    if (anim == [imageView.layer animationForKey:@"headerView"]) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            YWDownloadController3 *vc = [[YWDownloadController3 alloc] initWithNibName:@"YWDownloadController3" bundle:nil];
            [self.navigationController pushViewController:vc animated:YES];
        });
        
    }
    

}


//// ------------

#pragma mark - 横屏模式

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    
}
/**
 *  在此方法中修改布局
 */
-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    // 布局
    if(isLanscape)
    {
        
        self.tableView.hidden = YES;
        self.navBar.hidden = YES;
        
        self.view.backgroundColor = [UIColor blackColor];
        self.panGesture.enabled = YES;
        
        
        self.vedioView.bigScaleBtn.selected = YES;
        
        
        if (self.littleWindowVedioView.hidden == YES) { //小窗口不出现就是正在用vedioView
            
            [self.view addSubview:self.vedioBgView];
            
            self.vedioBgView.frame = CGRectMake(0, 0, Wi, He);
            
            self.vedioView.frame = self.vedioBgView.bounds;
            
            self.vedioBgView.layer.cornerRadius = 0;
        }
        else{ //正在使用小窗口
            [self.view addSubview:self.littleWindowVedioView];
            
            self.littleWindowVedioView.frame = CGRectMake(0, 0, Wi, He);
            
            self.littleWindowVedioView.layer.cornerRadius = 0;
            
        }
        
        
    }else
    {
        
        self.tableView.hidden = NO;
        self.navBar.hidden = NO;
        
        self.view.backgroundColor = [UIColor whiteColor];
        self.panGesture.enabled = NO;
        
        //加了这句就可以了、因为你把tableView的frame转换的时候tableView还是以横盘的参考对象、假如你写了layoutIfNeeded它就等你变成了竖屏再以竖屏的tableView为参考对象
        [self.view layoutIfNeeded];
        
        
        self.vedioView.bigScaleBtn.selected = NO;
        
        if (self.littleWindowVedioView.hidden == YES) { //小窗口不出现就是正在用vedioView
            
            //因为就算是headerView的vedioView在播放、竖屏后小窗口的宽高也被改变了、所以这里要重新设置小窗口的宽高
            CGFloat w = Wi/2.5;
            CGFloat h = w/1.5;
            self.littleWindowVedioView.width = w;
            self.littleWindowVedioView.height = h;
            
            [self.tableView addSubview:self.vedioBgView];
            self.vedioBgView.frame = CGRectMake(0, 0, Wi, headerViewVedioViewHeight);
            self.vedioView.frame = self.vedioBgView.bounds;
            
            self.vedioBgView.layer.cornerRadius = 0;
        }
        else{ //正在使用小窗口
            
            CGFloat w = Wi/2.5;
            CGFloat h = w/1.5;
            CGFloat y = self.view.height - h - littleWindowInterval - h;
            CGFloat x = Wi - w - littleWindowInterval;
            
            self.littleWindowVedioView.frame = CGRectMake(x, y, w, h);
            
            [self.view addSubview:_littleWindowVedioView];
            
            self.littleWindowVedioView.layer.cornerRadius = 5;
            
        }
        
        
        
        
        
        
        
        
        
    }


}

//放大/缩小
-(void)videoView:(YWVideoView3 *)videoView didClickBigScaleBtn:(UIButton *)btn{
    
    
//    btn.selected = !btn.selected;
    if (self.vedioView.bigScaleBtn.selected) {
           [self setViewOrientation:UIInterfaceOrientationPortrait];
    }
    else{
        
           [self setViewOrientation:UIInterfaceOrientationLandscapeRight];
    }
}




//强制横屏或竖屏
-(void)setViewOrientation:(UIInterfaceOrientation)orientation{

    if (@available(iOS 16.0, *)) {
        [UIApplication.sharedApplication.keyWindow.rootViewController setNeedsUpdateOfSupportedInterfaceOrientations];
              
              NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
              UIWindowScene *ws = (UIWindowScene *)array[0];
              UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [UIWindowSceneGeometryPreferencesIOS.alloc initWithInterfaceOrientations:1 << orientation];
              [ws requestGeometryUpdateWithPreferences:geometryPreferences
                                          errorHandler:^(NSError * _Nonnull error) {
              }];
//            @try {
//                NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
//                UIWindowScene *ws = (UIWindowScene *)array[0];
//                Class GeometryPreferences = NSClassFromString(@"UIWindowSceneGeometryPreferencesIOS");
//                id geometryPreferences = [[GeometryPreferences alloc]init];
//
//                if(orientation == UIInterfaceOrientationPortrait) {
//                    [geometryPreferences setValue:@(UIInterfaceOrientationMaskPortrait) forKey:@"interfaceOrientations"];
//                }
//                else {
//                    [geometryPreferences setValue:@(UIInterfaceOrientationMaskLandscapeRight) forKey:@"interfaceOrientations"];
//                }
//
//                SEL sel_method = NSSelectorFromString(@"requestGeometryUpdateWithPreferences:errorHandler:");
//                void (^ErrorBlock)(NSError *err) = ^(NSError *err){
//                      NSLog(@"调用了Block%@",err);
//                };
//                if ([ws respondsToSelector:sel_method]) {
//                    (((void (*)(id, SEL,id,id))[ws methodForSelector:sel_method])(ws, sel_method,geometryPreferences,ErrorBlock));
//                }
//            } @catch (NSException *exception) {
//                NSLog(@"*****************************华丽分割线**************************");
//                NSLog(@"%@",exception);
//            } @finally {
//
//            }
        } else {
            
            if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
                SEL selector = NSSelectorFromString(@"setOrientation:");
                NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
                [invocation setSelector:selector];
                [invocation setTarget:[UIDevice currentDevice]];
                int val = (int)orientation;
                [invocation setArgument:&val atIndex:2];
                [invocation invoke];

            }

        }
    
    

}

//////

// 本VC可以支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

// 本VC是否支持设备自动旋转
- (BOOL)shouldAutorotate
{
    return YES;
}

/**
 *  当屏幕即将旋转的时候调用
 *  @param toInterfaceOrientation 旋转完毕后的最终方向
 *  @param duration  旋转动画所花费的时间
 */
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{

    
    //切换屏幕方向时候把videoFunctionView设为透明效果会好点
//    self.videoFunctionView.alpha = 0;

    if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {// 横屏

    } else {//竖屏

    }

}

//开始成功代理
-(void)videoViewDidStartPlay:(YWVideoView3 *)videoView{
    
    //让整个程序能旋转
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotate = 1;
    
    
}

//停止成功代理
-(void)videoViewDidSotpPlay:(YWVideoView3 *)videoView{
    
    //让整个程序不能旋转
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotate = 0;
    
    
}





@end
